package com.xn.monitor.web.notify.mail;

import com.xn.monitor.entity.ServerEvent;
import com.xn.monitor.entity.ServerEventInfo;
import com.xn.monitor.web.notify.NotifyService;
import com.xn.monitor.web.service.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 邮件通知服务
 *
 * Created by yangshoujun on 2017/7/29 下午1:54.
 */
public class MailNotifyService implements NotifyService {

    public JavaMailSenderImpl mailSender;

    public JavaMailSenderImpl getMailSender() {
        return mailSender;
    }

    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void notify(ServerEventInfo eventObject) {
        try {
            if(eventObject.getEvent() == ServerEvent.UP) {
                return;
            }

            if(!Boolean.valueOf(PropertyUtils.get("mail.enabled"))) {
                return;
            }

            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setTo(PropertyUtils.get("mail.receiver"));
            mailMessage.setFrom(PropertyUtils.get("mail.username"));

            String subject = eventObject.getApplicationName() + " " + eventObject.getEvent().name() + " notify";
            mailMessage.setSubject(subject);

            String template = "Server %s is %s\nenv: %s\nnode: %s\ntime: %s\n";
            String content = String.format(template, eventObject.getApplicationName(),
                    eventObject.getEvent().name(), eventObject.getEnv(), eventObject.getName(),
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(eventObject.getTime())));
            mailMessage.setText(content);
            mailSender.send(mailMessage);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
    }
}
